import { Context, Schema, h } from 'koishi'

import {} from 'koishi-plugin-adapter-onebot';

export const name = 'longmsg-recall-combine'

export interface Config {
  maxTextLen: number
  maxImgNum: number
  quoteRemind: boolean
  combineRemind: boolean
  verboseSesssionOutput: boolean
  verboseConsoleOutput: boolean
}

export const Config: Schema<Config> = Schema.object({
  maxTextLen: Schema.number().description("最长文字数目").default(300),
  maxImgNum: Schema.number().description("最大图片数量").default(3),
  quoteRemind: Schema.boolean().description("session当场回复提醒消息过长").default(false),
  combineRemind: Schema.boolean().description("后续发的合并转发中提醒消息过长").default(true),
  verboseSesssionOutput: Schema.boolean().description("是否在会话消息中输出详细信息").default(false),
  verboseConsoleOutput: Schema.boolean().description("是否在控制台输出详细信息").default(false),
})

export function apply(ctx: Context, config: Config) {
  ctx.on('message', async(session) => {
    if ( !session.guildId ) {
      if (config.verboseConsoleOutput) 
        ctx.logger.info(`[longmsg-recall-combine] 非群组消息，跳过。`);
      return;
    }

    if ( session.onebot && session.userId !== session.bot.selfId ){
      const memberInfo = await session.onebot._request(
        "get_group_member_info",
        {
          group_id: session.guildId,
          user_id: session.userId
        }
    )

    if ( memberInfo?.data?.role !== "member" ){
      if ( config.verboseConsoleOutput)
          ctx.logger.info(`[longmsg-recall-combine] 是群主或者管理发消息，跳过。\n\t userid: ${session.userId}, username: ${session.username}`);
        return;
      }
    }


    let textLenCount = 0;
    let imgNumCount = 0;

    for ( const e of session.event.message.elements ){
      if ( e.type === 'text' ){
        textLenCount += e.attrs.content.length;
      }
      if ( e.type === 'img' ){
        imgNumCount += 1;
      }
    }

    if ( config.verboseConsoleOutput ){
      ctx.logger.info(`消息${session.content.slice(0,10)}的文字长度 = ${textLenCount}`);
      ctx.logger.info(`消息${session.content.slice(0,10)}的图片数量 = ${imgNumCount}`);
    }

    if ( textLenCount > config.maxTextLen || imgNumCount > config.maxImgNum ){
      ctx.logger.info(`消息过长${session.content.slice(0,10)}，长度超过${config.maxTextLen}, 正在尝试撤回并合并转发`);

      let remindMsg = h.at(session.userId) +  `的消息过长。已撤回+合并转发。\n`;
      if ( textLenCount > config.maxTextLen )
        remindMsg += `\n\t你发的文字总数是${textLenCount}, 最长文字总数是${config.maxTextLen}`;
      if ( imgNumCount > config.maxImgNum )
        remindMsg += `\n\t你发的图片总数是${imgNumCount}, 最多图片数目是${config.maxImgNum}`;
      remindMsg += `\n\n长消息记得合并转发哦~喵(>^ω^<)`

      if ( config.quoteRemind ){
        session.send(
          h.quote(session.messageId) + remindMsg
        )
      }

      try{
        let res_msg = h.escape( session.event.message.content );
        const sessionUser = await session.bot.getUser(session.userId, session.event.guild.id);
        const sessionGuildMember = await session.bot.getGuildMember(session.guildId, session.userId);
        const sessionBotSelf = await session.bot.getGuildMember(session.guildId, session.selfId);

        // const foo = session.bot.getGuildMember(session.guildId, session.userId);
        // foo.then( async (bar) => {
        //   await session.send(`[debug] qwq ${JSON.stringify(bar)}`)
        // })
        
        // await session.send(`[debug] qwq ${JSON.stringify(sessionGuildMember)}`)
        // await session.send(`[debug] qwq ${JSON.stringify(sessionBotSelf)}`)

        res_msg = `
        <message>
          <author id="${session.userId}" name="${session.username}"/>
            ${res_msg}
        </message>
        `;

        if( config.combineRemind ){
          // <author id="${session.bot.selfId}" name="${sessionBotSelf.name}"/>
          res_msg += `
          <message>
            <author id="${session.bot.selfId}" name="${sessionBotSelf.user.username}"/>
            ${remindMsg}
          </message>
        `;
        }

        res_msg += `
          <message>
            <p><b>日期:   </b>\t ${new Date().toLocaleString()} \n </p>
            <p><b>发送者: </b>\t ${sessionUser.name}  </p>\n 
            <p><b>群昵称: </b>\t ${session.username}  </p>\n 
            ${h.image(sessionUser.avatar)}
          </message>
        `;

        res_msg = `<message forward>\n` + res_msg + `</message>\n`;
        const origin_msg = h.unescape(res_msg);
        if ( config.verboseConsoleOutput )
          ctx.logger.info(`origin_msg = ${origin_msg.slice(0,50)}`)

        await session.send(origin_msg);
  
        await session.bot.deleteMessage(session.channelId, session.messageId);
      } catch (err){
        const errMsg = `消息长度>maxTextLen 或者 图片数目>maxImgLen，但是尝试撤回失败，请联系开发者VincentZyu. err = ${JSON.stringify(err)}`;

        if ( config.verboseSesssionOutput )
          await session.send(errMsg)

        // if ( config.verboseConsoleOutput )
          ctx.logger.info(errMsg);
      }
    }

    
  })
}
